package com.lei.sort;

import com.lei.linearsearch.ArrayGenerator;

/**
 * @Author LeiXiaoLei
 * @Date 2022/7/15 09:15
 * @Version 1.0
 */
public class InsertionSort {
    private InsertionSort() {
    }


    public static <E extends Comparable<E>> void sort(E[] arr) {
        for (int i = 1; i < arr.length; i++) {
            E temp = arr[i];
            for (int j = i; j - 1 >= 0; j--) {
                if (temp.compareTo(arr[j - 1]) < 0) arr[j] = arr[j - 1];
                else {
                    arr[j] = temp;
                    break;
                }
            }
        }
    }

    public static <E extends Comparable<E>> void sort4(E[] arr, int l, int r) {
        for (int i = l; i <= r; i++) {
            E temp = arr[i];
            int j;
            for (j = i; j - 1 >= l && temp.compareTo(arr[j - 1]) < 0; j--) {
                if (temp.compareTo(arr[j - 1]) < 0) arr[j] = arr[j - 1];
            }
            arr[j] = temp;
        }
    }

    public static <E extends Comparable<E>> void sort2(E[] arr) {
        for (int i = 0; i < arr.length; i++) {
            for (int j = i; j - 1 >= 0; j--) {
                if (arr[j].compareTo(arr[j - 1]) < 0) swap(arr, j, j - 1);
                else break;
            }
        }
    }


    public static <E extends Comparable<E>> void sort3(E[] arr) {
        for (int i = arr.length - 2; i >= 0; i--) {
            E temp = arr[i];
            for (int j = i; j < arr.length - 1; j++) {
                if (temp.compareTo(arr[j + 1]) > 0) arr[j] = arr[j + 1];
                else {
                    arr[j] = temp;
                    break;
                }
            }
        }
    }

    // 2 3 1 5, 2, 8, 10, 5
    private static <E> void swap(E[] arr, int i, int j) {
        E t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }

    public static void main(String[] args) {
        int[] dataSize = {10, 100, 1000, 10000, 100000};
        for (int n : dataSize) {
            Integer[] arr = ArrayGenerator.generatorRandomArray(n, n);
            SortingHelper.sortTest(InsertionSort.class, arr);
        }
    }
}
